import pandas as pd
import requests
import json
from retrying import retry

api_key = '04c8f778c4124f909fcea0df1d0cb992'


@retry(stop_max_attempt_number=3)
def get_recent_funding_rate(asset='BTC', market_type='C', **kwargs):
    header = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
        'coinglassSecret': api_key
    }

    if market_type == 'C':
        url = f"https://open-api.coinglass.com/public/v2/funding_coin_history?symbol={asset}&time_type=h8"
    else:
        url = f"https://open-api.coinglass.com/public/v2/funding_usd_history?symbol={asset}&time_type=h8"

    response = requests.request("GET", url, headers=header, timeout=15)
    res = json.loads(response.text)
    if 'data' not in res.keys():
        print(f'指标{asset}-{market_type}最新资金费率数据获取失败， 错误提示{res["msg"]}')
        return None
    else:
        res = res['data']
    if res['dateList']:
        res_list = []
        for item_key in ['dateList', 'frDataMap', 'priceList']:
            if item_key == 'frDataMap':
                for item in res[item_key]:
                    list_temp = res[item_key][item]
                    res_list.append(list_temp)
            else:
                list_temp = res[item_key]
                res_list.append(list_temp)
        df = pd.DataFrame(res_list).T
        df.columns = ['timestamp'] + list(res['frDataMap'].keys()) + ['price']
        print(f'指标{asset}-{market_type}最新资金费率数据获取成功')
        return df
    else:
        print(f'指标{asset}-{market_type}最新资金费率数据为空，无数据')
        return None


if __name__ == '__main__':
    get_recent_funding_rate()
